import { extend, type ResponseError } from "umi-request"

const errorHandler = (error: ResponseError & { description?: string }) => {
  if (error.response) {
    const { status, data } = error.response
    if (status === 401) {
      // TODO: 重定向到登录页面
      console.log("redirect to login page") 
    }
    return Promise.reject(data)
  }
  return Promise.reject(error)
}

// 扩展 umi-request --- 拦截错误
const request = extend({
  timeout: 10000,
  errorHandler,
})

// 请求拦截
request.interceptors.request.use((url, options) => {
  return { url, options }
})

// 响应拦截
request.interceptors.response.use((response) => {
  return new Promise((resolve, reject)=>{
    response.text().then(data => {
      let resData;
      try {
        resData = JSON.parse(data);
      } catch (error) {
        resData = { code: -1 };
      }
      if (resData.responseCode === 200) {
        resolve(resData);
      } else {
        reject(resData);
      }
    })
  })
})

export default request